package com.synjones.handsetS8.ild.pages;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.synjones.handsetS8.R;;
import com.synjones.handsetS8.facesdk.FaceAuthAsync;
import com.synjones.handsetS8.facesdk.FaceHandle;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.reader.IDCardReaderModule;

import java.util.HashMap;
import java.util.Map;

/**
 * 身份证读取
 */
public class IdCardReadActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int ALGORITHM_VERSION = 2;
    private Button btnPhotoGrph, btnManualInput;
    private ImageView ivBack;
    private TextView tvTitle;

    public IDCardReaderModule idCardReaderModule;
    private ReadCardThread ReadCardThreadhandler;
    private Bitmap bmp;
    //用于存放上一次读取成功的身份证信息
    private Map<String, Object> idCardInfo;
    private volatile boolean reading = false;

    private static final int ReadOnceDone = 0x01;
    private static final int ReadThreadDone = 0x09;

    //身份证信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_id_card_read);

        init();
    }

    /**
     * 初始化
     */
    private void init() {
        btnPhotoGrph = (Button) findViewById(R.id.btn_photo_graph);
        btnManualInput = (Button) findViewById(R.id.btn_manual_input);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);

        tvTitle.setText("身份证读取");

        btnPhotoGrph.setOnClickListener(this);
        btnManualInput.setOnClickListener(this);
        ivBack.setOnClickListener(this);

        idCardReaderModule = IDCardReaderModule.getInstance(this);
//        new OpenReaderAsync().execute();


        //开始读取
        resetIdCardInfo();
        startReadThread();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //拍照录入
            case R.id.btn_photo_graph:
                intent = new Intent(this, PhotoGraphActivity.class);
                break;
            //手动录入
            case R.id.btn_manual_input:
                intent = new Intent(this, ManualInputActivity.class);
                break;
            //返回
            case R.id.iv_back:
                finish();
                return;
            default:
                break;
        }
        startActivity(intent);
    }

    /**
     * 重置身份证信息
     */
    private void resetIdCardInfo() {
        //清除信息显示
        //tvIdInfo.setText("请读取身份证");
        //清除头像
        bmp = null;
        //ivIdPhoto.setImageBitmap(null);
        //清除缓存身份证信息
        idCardInfo = null;
    }

    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        stopRead();
        idCardReaderModule.close();
    }

    void startReadThread() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();
    }

    private void stopRead() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            try {
                ReadCardThreadhandler.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ReadCardThreadhandler = null;
        }
    }

    //主要通过IDCard对象函数显示身份证信息和照片，
    public void showIDcardInfo(IDCard card) {
        if (null == card) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        sb
                .append("姓名: ").append(card.getName())
                .append("\n性别: ").append(card.getSex())
                .append("\n生日: ")
                .append(card.getYearOfBirth()).append("年")
                .append(card.getMonthOfBirth()).append("月")
                .append(card.getDayOfBirth()).append("日")
                .append("\n住址: ").append(card.getAddress())
                .append("\n公民身份号码: ").append(card.getIDCardNo())
                .append("\n发证机关: ").append(card.getGrantDept())
                .append("\n有效期限: ")
                .append(card.getUserLifBebinWithPoint())
                .append("-")
                .append(card.getUserLifEndWithPoint());

        //tvIdInfo.setText(sb.toString());
        Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();

        //将数据存起来
        idCardInfo = new HashMap<>(16);
        idCardInfo.put("name", card.getName());
        idCardInfo.put("idcardno", card.getIDCardNo());
        idCardInfo.put("sex", card.getSex());
        idCardInfo.put("nation", card.getNation());
        idCardInfo.put("birthday", card.getBirthday());
        idCardInfo.put("address", card.getAddress());
        idCardInfo.put("grantdept", card.getGrantDept());
        idCardInfo.put("userlifebegin", card.getUserLifeBegin());
        idCardInfo.put("userlifeend", card.getUserLifeEnd());
        idCardInfo.put("appendAddress", card.getAppendAddress());
        idCardInfo.put("fpName", card.getFpName());
        idCardInfo.put("readTime", card.getReadTime());

        //加载头像
        try {
            //int result = idcard.decodeResult;
            if (bmp != null) bmp.recycle();
            bmp = card.getPhoto();
            if (bmp != null) {//保存照片
                //MediaStore.Images.Media.insertImage(getContentResolver(), bmp, "zp", "");
                //String bmpPath = getFileStreamPath("photo.bmp").getAbsolutePath();
                //util_File.copyfile(bmpPath,util_File.getExternalPath()+idcard.getName()+".bmp");
            } else {
                Resources res = getResources();
                bmp = BitmapFactory.decodeResource(res, R.drawable.photo);
            }
            //ivIdPhoto.setImageBitmap(bmp);
            ////log.debug("decode wlt finish");
            System.gc();
        } catch (Exception ioe) {
            ioe.printStackTrace();
            //log.debug("photo display error:" + ioe.getMessage());
            //tvMessage.setText("状态：照片显示错" + ioe.getMessage());
        }

        //跳转到信息填写页面
        Intent intent = new Intent(IdCardReadActivity.this, ManualInputActivity.class);
        intent.putExtra("worker_name", card.getName());
        intent.putExtra("id_card_no", card.getIDCardNo());
        startActivity(intent);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (ReadOnceDone == msg.what) {
                //读卡成功，显示身份证信息
                showIDcardInfo((IDCard) msg.obj);
            }
            super.handleMessage(msg);
        }
    };

    class ReadCardThread extends Thread {
        public void run() {
            OpenReader();
            if (!idCardReaderModule.isOpen()) {
                reading = false;
                idCardReaderModule.close();
                Log.e("ReadCardThread", "读卡器打开失败");
            } else {
                Log.e("ReadCardThread", "读卡器打开成功");
            }

            while (reading) {
                try {
                    //getIDcardInfo()只读身份证信息，不读取指纹信息。 等同于getIDcardInfo(false, true, false);
                    IDCardReaderRetInfo retInfo;
                    //retInfo = idCardReaderModule.getIDcardInfo(false, true, true);
                    retInfo = idCardReaderModule.getIDcardInfo();

                    //读取指纹信息，读卡时间会稍长  可参考指纹的activity中读取身份证指纹按钮的实现
                    //IDCardReaderRetInfo retInfo = idCardReaderModule.getIDcardInfo(boolSameCardReadOnce, boolDecodePhoto, boolReadFringerprint);
                    //samvID=idCardReaderModule.getSamvIDString();//获取公安部二代证模块编号
                    //String appendAddress=idCardReaderModule.getAppendAddress();//获取身份证内的追加地址信息
                    if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
                        //if(boolReadFringerprint)//仅测试时读取追加信息
                        //	retInfo.card.setAppendAddress(idCardReaderModule.getAppendAddress());
                        mHandler.obtainMessage(ReadOnceDone, retInfo.card).sendToTarget();
                        Thread.sleep(500);
                    } else if (retInfo.errCode == IDCardReaderRetInfo.ERROR_RECV_FINDCARD) {
                        Log.e("ReadCardThread", "通信错误,重新打开读卡器");
                        idCardReaderModule.close();
                        Thread.sleep(3000);
                        idCardReaderModule.open();
                        if (!idCardReaderModule.isOpen()) {
                            reading = false;
                            idCardReaderModule.close();
                            Log.e("ReadCardThread", "读卡器打开失败");
                        }
                    } else {
                        mHandler.obtainMessage(ReadOnceDone, null).sendToTarget();
                        Thread.sleep(200);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }//while

            mHandler.obtainMessage(ReadThreadDone).sendToTarget();

        }//run

        public void StopRead() {
            reading = false;
            interrupted();
        }

    }//

//    /**
//     * 打开读卡器和人脸识别器
//     */
//    class OpenReaderAsync extends AsyncTask<Void, Void, Boolean> {
//
//        @Override
//        protected Boolean doInBackground(Void... voids) {
//            idCardReaderModule.open();
//            return idCardReaderModule.isOpen();
//        }
//
//        @Override
//        protected void onPreExecute() {
//            super.onPreExecute();
//            //setupProgressDialog("正在打开读卡器，请稍等", null);
//        }
//
//        @Override
//        protected void onPostExecute(Boolean aBoolean) {
//            super.onPostExecute(aBoolean);
//            try {
//                //progressDialog.dismiss();
//            } catch (Exception e) {
//            }
//            if (!aBoolean) {
//                Toast.makeText(IdCardReadActivity.this, "读卡器打开失败", Toast.LENGTH_SHORT).show();
//            }
//
//            new FaceAuthAsync(IdCardReadActivity.this, FaceHandle.getFaceSDKInstance(ALGORITHM_VERSION)).setOnfinish(new FaceAuthAsync.OnFinish() {
//                @Override
//                public void onDone(boolean initOk, int errCode) {
//                    if (!initOk)
//                        Toast.makeText(IdCardReadActivity.this, "人脸初始化错误，errcode=" + errCode, Toast.LENGTH_SHORT).show();
//                }
//            }).execute();
//
//            //开始读取
//            resetIdCardInfo();
//            startReadThread();
//        }
//    }
}